package com.zty.netty;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

/**
 * @Author ZTY
 * @Description Netty服务端
 * @Date 16:04 2023-12-06
 **/

public class AppServer {

    // 将服务端绑定在一个端口上
    private int port;

    public AppServer(int port) {
        this.port = port;
    }

    // 启动服务端
    public void start(){
        // 创建EventLoopGroup，老板只负责处理客户端请求，之后会将请求分发给工人
        NioEventLoopGroup boss = new NioEventLoopGroup();

        // worker可有多个   官方默认老板两个，工人10个
        NioEventLoopGroup worker = new NioEventLoopGroup();

        try {
            // 需要一个引导器引导程序
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            // 配置服务器
            serverBootstrap = serverBootstrap.group(boss,worker)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            // 添加一个处理器，即一个流水线上的类处理消息
                            socketChannel.pipeline().addLast(new MyChannelHandler());

                        }
                    });

            // 绑定端口
            ChannelFuture channelFuture = serverBootstrap.bind(port).sync();
            channelFuture.channel().closeFuture().sync();
        }catch (InterruptedException e){
            e.printStackTrace();
        }finally {

            try {
                boss.shutdownGracefully().sync();
                worker.shutdownGracefully().sync();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        new AppServer(8080).start();
    }
}
